<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
	<meta name="format-detection" content="telephone=no" />
	<title>速翔网络 - QQ技术：1424445608</title>
	<link rel="stylesheet" type="text/css" href="../c/aui.css" />
	<link rel="stylesheet" type="text/css" href="../c/sixin.css" />
	<style>
		/*body {
			background: #EBEBEB;
		}*/

		#sx-view {
			width: 100%;
			height: 100%;
			overflow: hidden;
		}

		.voice {
			position: relative;
			background-image: url(../i/UIChatBox/stop.png);
			background-repeat: no-repeat;
			background-position: 0 -0.1rem;
			background-size: 1.4rem auto;
			padding-left: 1.4rem;
			padding-right: 1.4rem;
			color: #424242;
		}

		.voice_s {
			background-image: url(../i/UIChatBox/playing.gif);
			background-repeat: no-repeat;
			background-position: 0 -0.1rem;
			background-size: 1.4rem auto;
		}

		.aui-chat .aui-chat-header {
			margin-bottom: 0px;
		}

		.aui-chat .aui-chat-content {
			color: #212121;
			font-size: 0.75rem;
			border-radius: 0.2rem;
			position: relative;
			padding: 0.3rem;
			word-break: break-all;
			word-wrap: break-word;
		}

		.aui-chat .aui-chat-content img {
			max-width: 100%;
			display: inline;
			border-radius: 0.2rem;
			vertical-align: middle
		}

		.aui-chat .aui-chat-left .aui-chat-content {
			float: left;
			left: 0.5rem;
		}

		.aui-chat .aui-chat-right .aui-chat-content {
			right: 0.5rem;
			float: right;
		}
	</style>
</head>

<body>
	<section class="aui-chat" id="sx-view"></section>

</body>
<script type="text/javascript" src="../j/api.js"></script>
<script type="text/javascript">
	var rong, id = 0,
		roots = 1,
		UIPhotoViewer, UIChatBox,extra_user
	apiready = function() {
		_user = _getPrefs('_user');
		id = "" + api.pageParam['id'];
		if (!api.pageParam['id']) {
			_alert('id错误', function(ret) {
				_close();
			})
		}
		rong = api.require('rongCloud2');
		UIChatBox = api.require('UIChatBox');
		UIPhotoViewer = api.require('UIPhotoViewer');
		init();
		// 应用从后台回到前台事件
		api.addEventListener({
			name: 'resume'
		}, function(ret, err) {

		});
		//监听 recordBtn 按住语音
		UIChatBox.addEventListener({
			target: 'recordBtn',
			name: 'press'
		}, function(ret, err) {
			if (ret) {
				//    console.log("语音开始ret："+JSON.stringify(ret));
				sj1 = new Date().getTime();
				if (ret) {
					var savePath = 'fs://cgg_' + (+new Date()) + '.amr';
					api.startRecord({
						path: savePath
					});
					//   console.log(savePath)
				}
			} else {
				console.log("语音开始err：" + JSON.stringify(err));
			}
		});
		//监听 recordBtn 松开语音
		UIChatBox.addEventListener({
			target: 'recordBtn',
			name: 'press_cancel'
		}, function(ret, err) {
			if (ret) {
				//    console.log("我松开了ret："+JSON.stringify(ret));
				var sj2 = new Date().getTime() - sj1;
				if (sj2 <= 2000) {
					stopRecord();
					_msg('语音时间较短，请重新录音')
				} else if (sj2 > 2000) {
					api.stopRecord(function(ret, err) {
						if (ret.duration > 0) {
							// 发送语音
							sendVoiceMessage(ret.path, ret.duration);
						}
					});
				}
			} else {
				console.log("我松开了err：" + JSON.stringify(err));
			}
		});
		var winHeight = api.winHeight;
		UIChatBox.addEventListener({
			target: 'inputBar',
			name: 'move'
		}, function(ret, err) {
			if (ret) {
				if (api.systemType == 'ios') {
					$api.css($api.dom('#sx-view'), 'padding-bottom:' + ret.panelHeight + 'px');
				}
				_gun();
			}
		});
		rong.setOnReceiveMessageListener(function(ret, err) {
			if (ret.result.message) {
				_html(ret.result.message);
				clearMessagesUnreadStatus();
			}
		})
		// 接受消息
		// api.addEventListener({
		//     name: 'xiaoxi_data'
		// }, function(ret, err) {
		// 		_html(ret.value);
		// 		clearMessagesUnreadStatus();
		// });

	}

	function init() {
		// 弹出聊天框
		i();
		// 获取聊天记录
		_getLatestMessages();
		// 清除某一会话的消息未读状态
		clearMessagesUnreadStatus();
	}
	// 插入html消息
	function _html(ret) {

		if(!ret.content){
			return;
		}
		if (!ret.content.extra) {
			ret.content.extra = "{uid:" + _user.id + ",img:'" + _user.img + "',nickname:'" + _user.username + "'}";
		} else {}
		//	ret.content.extra = '{nickname:"1",img:"2"}'
		var extra = eval('(' + ret.content.extra.replace(/}{/, ',') + ')');
//		var extra = ret.content.extra
	//	console.log(extra);

		var extra = _message_user(extra_user);

		var text = ret.content.text;
		var idclass = ret.senderUserId == _user.id ? 'right' : 'left';
		var html = '<div class="aui-chat-item aui-chat-' + idclass + '">';
		html += '<div class="aui-chat-media">';
		var img = ret.senderUserId == _user.id ? _user.img : extra.img;
		html += '<img src="' + (img ? _img(img,60) : '../i/touxiang.png')  + '"  />';
		html += '</div>';
		html += '<div class="aui-chat-inner">';
		html += '<div class="aui-chat-name">';
		html += ret.senderUserId == _user.id ? _user.username : extra.nickname;
		html += '</div>';
		html += '<div class="aui-chat-content">';
		html += '<div class="aui-chat-arrow"></div>';
		if (ret.objectName == 'RC:TxtMsg') {
			html += _text(ret.content.text);
			//	console.log(html)
		} else if (ret.objectName == 'RC:ImgMsg') {
			html += '<img src="' + ret.content.thumbPath + '" tapmode onclick="img(\'' + ret.content.imageUrl + '\')" />';
		} else if (ret.objectName == 'RC:VcMsg') {
			html += '<div class="voice" tapmode onclick="play(this,\'' + ret.content.voicePath + '\')">' + ret.content.duration + '</div>';
		} else {
			html += JSON.stringify(ret);
		}
		html += '</div></div></div>';
		//	console.log(html)
		$api.append($api.dom('#sx-view'), html);
		api.parseTapmode();
		_gun();
		return;
		if (roots == 1) {
			var scrollHeight = $(document).height();
			//文档高度
			window.scrollTo(0, scrollHeight);
			//到达文档底部
		} else {
			_gun();
		}

	}



	// 获取最新聊天记录
	function _getLatestMessages() {
		// 之前调用 init 和 connect 的代码省略
		rong.getLatestMessages({
			conversationType: 'PRIVATE',
			targetId: id,
			count: 100
		}, function(ret, err) {
		//	console.log(JSON.stringify(ret))
			if (ret) {
				if (ret.status == 'success') {
					if(ret.result.length){
						var i_s = ret.result.length - 1;
						extra_user = _extra(ret.result[i_s].content.extra);
						for (var i = 0; i < ret.result.length; i++) {
							_html(ret.result[i_s]);
							i_s--
						}
					}
				}
			}
			if(!extra_user){
				extra_user = {
					a:{uid:_user.id,img:_user.img,nickname:_user.username},
					b:api.pageParam['user']
				}
			}
			// // 设置顶部标题
			api.execScript({
			    script: "$api.html($api.dom('.aui-title'),'"+_message_user(extra_user).nickname+"')"
			});

		})
	}

	//终止录音
	function stopRecord() {
		api.stopRecord(function(ret, err) {});
	}

	//播放录音
	function play(_this, path) {
		//console.log(path)
		_this = $(_this);
		_this.addClass('voice_s');
		api.startPlay({
			path: path
		}, function() {
			_this.removeClass('voice_s')
		});
	}

	// 打开图片
	function img(images) {
		UIPhotoViewer.open({
			images: [images],
			bgColor: '#000',
			mode: 2
		}, function(ret, err) {
			if (ret.eventType == 'click') {
				UIPhotoViewer.close();
			}
		});
	}

	// 聊天框
	function i() {
		UIChatBox.open({
			placeholder: '发送消息...',
			maxRows: 4,
			emotionPath: _i + 'UIChatBox/emotion',
			texts: {
				recordBtn: {
					normalTitle: '按住说话',
					activeTitle: '松开结束'
				},
				sendBtn: {
					title: '发送'
				}
			},
			styles: {
				topDivider:{                        //(可选项)顶部分割线配置
			    width:1,                        //(可选项)顶部分割线的粗细，默认：0
			    color:'#000'                    //(可选项)顶部分割线的颜色；默认：#000 ;支持图片设置(fs:// & widget://)
		    },
				inputBar: {
					borderColor: '#161823',
					bgColor: '#161823',
					textColor: '#fff'
				},
				inputBox: {
					borderColor: '#161823',
					bgColor: '#242630',
					borderCorner:15
				},
				recordBtn: {
					normalBg: '#c4c4c4',
					activeBg: '#999999',
					color: '#000',
					size: 14
				},
				indicator: {
					target: 'both',
					color: '#c4c4c4',
					activeColor: '#9e9e9e'
				},
				sendBtn: {
					titleColor: '#fff',
					bg: '#000',
					activeBg: '#46a91e',
					titleSize: 14
				},
				emotionBtn: {
					normalImg: _i + 'UIChatBox/face1.png'
				},
				extrasBtn: {
					normalImg: _i + 'UIChatBox/add1.png'
				},
				keyboardBtn: {
					normalImg: _i + 'UIChatBox/key1.png'
				},
				recordPanelBtn: { //JSON对象；录音面板样式
					normalImg: '', //（可选项）字符串类型；按钮常态的图片
					activeImg: '', //（可选项）字符串类型；按钮按下时的图片
					width: 100, //（可选项）数字类型；按钮的宽度，默认：100
					height: 100 //（可选项）数字类型；按钮的高度，默认：100
				},
				speechBtn : {
					normalImg : _i + 'UIChatBox/rec.png'
				},
			},
			extras: {
				titleSize: 10,
				titleColor: '#a3a3a3',
				btns: [{
					title: '相册图片',
					normalImg: _i + 'UIChatBox/img1.png',
					activeImg: _i + 'UIChatBox/img2.png'
				}, {
					title: '相机拍照',
					normalImg: _i + 'UIChatBox/cam1.png',
					activeImg: _i + 'UIChatBox/cam2.png'
				}]
			},
		}, function(ret, err) {
			if (ret) {
				//console.log("ret：" + JSON.stringify(ret));
				// 发送按钮
				if (ret.eventType == 'send') {
					// 开始发送
					sendTextMessage(ret.msg);
				}
				// 点击+
				if (ret.eventType == 'clickExtras') {
					_images(ret.index)
				}
			} else {
				//	console.log("err：" + JSON.stringify(err));
			}
		});
	}

	// 发送文字消息
	function sendTextMessage(text) {

		rong.sendTextMessage({
			conversationType: 'PRIVATE',
			targetId: id,
			text: text,
			extra: JSON.stringify(extra_user)
		}, function(ret, err) {
			if (ret) {
			//	console.log(JSON.stringify(ret))
				if (ret.status == 'success' || ret.status == 'prepare') {
					_html(ret.result.message);
					// 更新聊天列表
					gengxin(ret.result.message);
				}
			} else {
				sendTextMessage_err(err.code)
			}
		});
	}

	// 发送图片
	function sendImageMessage(img) {

		rong.sendImageMessage({
			conversationType: 'PRIVATE',
			targetId: id,
			imagePath: img,
			extra: JSON.stringify(extra_user)
		}, function(ret, err) {
			if (ret) {
				if (ret.status == 'prepare') {
					_html(ret.result.message);
					// 更新聊天列表
					gengxin(ret.result.message);
				}
			} else {
				sendTextMessage_err(err.code)
			}
		});
	}

	// 发送语音
	function sendVoiceMessage(voicePath, duration) {
		rong.sendVoiceMessage({
			conversationType: 'PRIVATE',
			targetId: id,
			voicePath: voicePath,
			duration: duration,
			extra: JSON.stringify(extra_user)
		}, function(ret, err) {
			if (ret) {
				if (ret.status == 'prepare') {
					_html(ret.result.message);
					// 更新聊天列表
					gengxin(ret.result.message);
				}
			} else {
				sendTextMessage_err(err.code)
			}
		});
	}

	// 选择图片或拍照上传
	function _images(index) {
		var sourceType = 'library'
		if (index == 1) {
			sourceType = 'camera';
		}
		api.getPicture({
			sourceType: sourceType,
			encodingType: 'png',
			mediaValue: 'pic',
			destinationType: 'url',
			quality: 20,
			saveToPhotoAlbum: false
		}, function(ret, err) {
			if (ret) {
				sendImageMessage(ret.data)
			} else {
				//    console.log("err："+JSON.stringify(err));
			}
		});
	}

	// 发送失败返回信息
	function send_err(msg) {
		switch (msg) {
			case '30014':
				_alert('发送处理失败，错误码：' + msg)
				break;
			case '30003':
				_alert('服务器超时，错误码：' + msg)
				break;
			case '31009':
				_alert('用户被屏蔽，错误码：' + msg)
				break;
			case '-10000':
				_alert('未调用 init 方法进行初始化，错误码：' + msg)
				break;
			case '-10001':
				_alert('未调用 connect 方法进行连接，错误码：' + msg)
				break;
			case '-10002':
				_alert('输入参数错误，错误码：' + msg)
				break;
			default:
				_alert('用户在黑名单中，错误码：' + msg);
		}
	}


	// 滚动顶部
	function _gun(type) {
		var time = 300
		setTimeout(function() {
			api.pageDown({
				bottom: true,
				animate: true
			}, function(ret) {});
		}, time || 0)
	}
	// 清除某一会话的消息未读状态
	function clearMessagesUnreadStatus() {
		rong.clearMessagesUnreadStatus({
			conversationType: 'PRIVATE',
			targetId: id
		}, function(ret, err) {
			api.execScript({
					name: 'root',
					script: 'getTotalUnreadCount();'
			});
		})
	}
	function gengxin(data){
		if(!data.content){
			return;
		}
		// 消息页传播内容
		api.sendEvent({
				name: 'xiaoxi_data',
				extra: data
		});
	}
</script>

</html>
